<template>
  <view class="post-edit-container">
    <view class="edit-header">
      <view class="header-title">{{ isEditing ? '编辑帖子' : '发布新帖子' }}</view>
      <button class="publish-btn" @click="savePost">发布</button>
    </view>
    
    <view class="edit-form">
      <input class="post-title-input" v-model="postForm.title" placeholder="请输入标题" maxlength="50" />
      <view class="title-count">{{ postForm.title.length }}/50</view>
      
      <textarea class="post-content-textarea" v-model="postForm.content" placeholder="请输入内容" maxlength="1000" />
      <view class="content-count">{{ postForm.content.length }}/1000</view>
      
      <view class="upload-images">
        <view class="images-list">
          <view class="image-item" v-for="(img, index) in postForm.images" :key="index">
            <image :src="img" mode="aspectFill" class="uploaded-image"></image>
            <text class="delete-image-btn" @click="removeImage(index)">×</text>
          </view>
          
          <view class="add-image-btn" @click="chooseImage" v-if="postForm.images.length < 9">
            <view class="icon-svg" v-html="generalIcons.camera"></view>
            <text class="add-text">添加图片</text>
          </view>
        </view>
        <text class="image-hint">最多上传9张图片</text>
      </view>
      
      <view class="form-item tag-selector">
        <text class="form-label">选择标签</text>
        <view class="tags-list">
          <view 
            v-for="tag in availableTags" 
            :key="tag.value"
            class="tag-item"
            :class="{ selected: postForm.tags.includes(tag.value) }"
            @click="toggleTag(tag.value)"
          >
            {{ tag.name }}
          </view>
        </view>
      </view>
      
      <view class="form-item location-selector">
        <text class="form-label">位置信息 <text class="optional">(选填)</text></text>
        <view class="location-input" @click="chooseLocation">
          <view class="icon-svg" v-html="generalIcons.location"></view>
          <text class="location-text">{{ postForm.location || '添加位置' }}</text>
          <view class="icon-svg right-icon" v-html="generalIcons.right"></view>
        </view>
      </view>
    </view>
    
    <view class="bottom-actions">
      <button class="cancel-btn" @click="cancelEdit">取消</button>
      <button class="save-btn" @click="savePost">发布</button>
    </view>
  </view>
</template>

<script>
import { usePostStore } from '@/store/postStore';
import { generalIcons } from '@/static/icons/icon-svg';

export default {
  data() {
    return {
      isEditing: false,
      postId: null,
      generalIcons: generalIcons,
      postForm: {
        title: '',
        content: '',
        images: [],
        tags: [],
        location: ''
      },
      availableTags: [
        { name: '无障碍设施', value: 'accessibility' },
        { name: '活动', value: 'event' },
        { name: '建议', value: 'suggestion' },
        { name: '问题', value: 'problem' },
        { name: '分享', value: 'share' },
        { name: '其他', value: 'other' }
      ]
    };
  },
  
  onLoad(options) {
    try {
      console.log('帖子编辑页面加载', options);
      
      // 添加延迟处理，避免页面闪退
      setTimeout(() => {
        this.initForm(options);
      }, 100);
    } catch (error) {
      console.error('帖子编辑页面加载错误:', error);
      uni.showToast({
        title: '页面加载错误',
        icon: 'none'
      });
    }
  },
  
  methods: {
    // 新增初始化表单方法
    initForm(options) {
      try {
        if (options && options.id) {
          console.log('正在编辑帖子:', options.id);
          this.isEditing = true;
          this.postId = options.id;
          this.loadPostData();
        } else {
          console.log('创建新帖子');
          this.isEditing = false;
          this.postId = null;
          // 初始化表单
          this.postForm = {
            title: '',
            content: '',
            images: [],
            tags: [],
            location: ''
          };
        }
      } catch (error) {
        console.error('表单初始化错误:', error);
        uni.showToast({
          title: '初始化表单失败',
          icon: 'none'
        });
      }
    },
    
    loadPostData() {
      try {
        const postStore = usePostStore();
        const post = postStore.getPostById(this.postId);
        
        if (post) {
          this.postForm = {
            title: post.title || '',
            content: post.content || '',
            images: post.images || [],
            tags: post.tags || [],
            location: post.location || ''
          };
        } else {
          uni.showToast({
            title: '帖子不存在',
            icon: 'none'
          });
          setTimeout(() => {
            // this.navigateBack();
          }, 1500);
        }
      } catch (error) {
        console.error('加载帖子数据错误:', error);
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
      }
    },
    
    chooseImage() {
      try {
        const maxCount = 9 - this.postForm.images.length;
        
        console.log('准备选择图片，最多可选', maxCount);
        
        if (maxCount <= 0) {
          uni.showToast({
            title: '最多只能上传9张图片',
            icon: 'none'
          });
          return;
        }
        
        // 显示加载提示
        uni.showLoading({
          title: '选择图片中...'
        });
        
        uni.chooseImage({
          count: maxCount,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            try {
              console.log('选择图片成功，数量:', res.tempFilePaths.length);
              // 处理返回的图片路径
              const tempFilePaths = res.tempFilePaths;
              
              // 检查文件大小，过大的文件可能导致问题
              let validImages = [];
              let hasLargeImages = false;
              
              for (let i = 0; i < tempFilePaths.length; i++) {
                try {
                  const fileInfo = uni.getFileSystemManager().statSync(tempFilePaths[i]);
                  console.log(`图片 ${i+1} 大小:`, fileInfo.size);
                  
                  // 如果图片大于5MB，视为过大
                  if (fileInfo.size > 5 * 1024 * 1024) {
                    hasLargeImages = true;
                    console.warn(`图片 ${i+1} 太大，可能导致问题`);
                  } else {
                    validImages.push(tempFilePaths[i]);
                  }
                } catch (statError) {
                  console.error('获取文件信息失败:', statError);
                  // 无法获取文件信息时，仍然添加图片
                  validImages.push(tempFilePaths[i]);
                }
              }
              
              if (hasLargeImages) {
                uni.showToast({
                  title: '部分图片较大，已进行优化',
                  icon: 'none',
                  duration: 2000
                });
              }
              
              // 更新表单中的图片列表
              this.postForm.images = [...this.postForm.images, ...validImages];
              
              uni.hideLoading();
            } catch (innerError) {
              uni.hideLoading();
              console.error('处理图片数据错误:', innerError);
              uni.showToast({
                title: '处理图片失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            uni.hideLoading();
            console.error('选择图片失败:', err);
            
            // 如果用户取消了选择，不显示错误提示
            if (err.errMsg && err.errMsg.indexOf('cancel') >= 0) {
              console.log('用户取消了选择图片');
              return;
            }
            
            uni.showToast({
              title: '选择图片失败',
              icon: 'none'
            });
          },
          complete: () => {
            // 确保加载提示被隐藏
            setTimeout(() => {
              uni.hideLoading();
            }, 300);
          }
        });
      } catch (error) {
        uni.hideLoading();
        console.error('选择图片错误:', error);
        uni.showToast({
          title: '无法打开相册',
          icon: 'none'
        });
      }
    },
    
    removeImage(index) {
      this.postForm.images.splice(index, 1);
    },
    
    toggleTag(tagValue) {
      const index = this.postForm.tags.indexOf(tagValue);
      if (index === -1) {
        this.postForm.tags.push(tagValue);
      } else {
        this.postForm.tags.splice(index, 1);
      }
    },
    
    chooseLocation() {
      uni.chooseLocation({
        success: (res) => {
          this.postForm.location = res.name;
        }
      });
    },
    
    savePost() {
      if (!this.validateForm()) return;
      
      try {
        console.log('准备保存帖子');
        
        const postStore = usePostStore();
        let result;
        
        if (this.isEditing) {
          // 更新帖子
          console.log('更新现有帖子:', this.postId);
          result = postStore.updatePost(this.postId, this.postForm);
          
          if (result) {
            uni.showToast({
              title: '更新成功',
              icon: 'success'
            });
            setTimeout(() => {
              this.navigateBack();
            }, 1500);
          } else {
            throw new Error('更新帖子失败');
          }
        } else {
          // 创建新帖子
          console.log('创建新帖子，表单数据:', JSON.stringify(this.postForm));
          
          try {
            // 确保表单数据被正确处理
            const postData = {
              title: this.postForm.title.trim(),
              content: this.postForm.content.trim(),
              images: [...this.postForm.images], // 创建一个新数组，避免引用问题
              tags: [...this.postForm.tags],
              location: this.postForm.location
            };
            
            console.log('处理后的帖子数据:', JSON.stringify(postData));
            result = postStore.addPost(postData);
            
            if (result) {
              console.log('新帖子创建成功，ID:', result.id);
              uni.showToast({
                title: '发布成功',
                icon: 'success',
                duration: 2000
              });
              
              // 确保帖子数据被保存到存储
              postStore.savePostsToStorage();
              
              setTimeout(() => {
                // 返回到前一页，刷新社区页面
                uni.navigateBack({
                  delta: 1,
                  success: () => {
                    console.log('导航返回成功，发送刷新事件');
                    // 发布成功后，发送一个刷新社区页面的事件
                    uni.$emit('refreshCommunity');
                  },
                  fail: (err) => {
                    console.error('导航返回失败:', err);
                  }
                });
              }, 1500);
            } else {
              console.error('创建帖子返回结果为空');
              throw new Error('创建帖子失败，返回结果为空');
            }
          } catch (innerError) {
            console.error('处理帖子数据错误:', innerError);
            throw innerError;
          }
        }
      } catch (error) {
        console.error('保存帖子错误:', error.message, error.stack);
        uni.showToast({
          title: '发布失败，请重试',
          icon: 'none'
        });
      }
    },
    
    validateForm() {
      if (!this.postForm.title.trim()) {
        uni.showToast({
          title: '请输入标题',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.postForm.content.trim()) {
        uni.showToast({
          title: '请输入内容',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    cancelEdit() {
      uni.showModal({
        title: '提示',
        content: '确定放弃编辑吗？',
        success: (res) => {
          if (res.confirm) {
            this.navigateBack();
          }
        }
      });
    },
    
    navigateBack() {
      uni.navigateBack();
    }
  }
};
</script>

<style>
.post-edit-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #fff;
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f2f5;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
}

.publish-btn {
  background-color: #3F7BFC;
  color: #fff;
  font-size: 28rpx;
  padding: 10rpx 40rpx;
  border-radius: 30rpx;
  margin: 0;
}

.edit-form {
  flex: 1;
  padding: 30rpx;
}

.post-title-input {
  height: 100%;
  width: 100%;
  font-size: 32rpx;
  font-weight: bold;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f2f5;
  color: #333;
}

.title-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.post-content-textarea {
  width: 100%;
  height: 300rpx;
  font-size: 28rpx;
  line-height: 1.5;
  padding: 20rpx 0;
  margin-top: 20rpx;
  color: #333;
}

.content-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.upload-images {
  margin-top: 40rpx;
}

.images-list {
  display: flex;
  flex-wrap: wrap;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
}

.delete-image-btn {
  position: absolute;
  top: -20rpx;
  right: -20rpx;
  width: 40rpx;
  height: 40rpx;
  line-height: 36rpx;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  border-radius: 50%;
  font-size: 32rpx;
}

.add-image-btn {
  width: 200rpx;
  height: 200rpx;
  border: 1px dashed #ddd;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
}

.add-image-btn .icon-svg {
  width: 32px;
  height: 32px;
  margin-bottom: 10rpx;
}

.add-image-btn .icon-svg svg {
  width: 100%;
  height: 100%;
}

.add-text {
  font-size: 24rpx;
}

.image-hint {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.form-item {
  margin-top: 40rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
}

.tag-item {
  padding: 10rpx 30rpx;
  background-color: #f0f2f5;
  border-radius: 30rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  font-size: 24rpx;
  color: #666;
}

.tag-item.selected {
  background-color: #3F7BFC;
  color: #fff;
}

.location-input {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f2f5;
}

.location-input .icon-svg {
  color: #3F7BFC;
  margin-right: 10rpx;
}

.location-input .right-icon {
  margin-left: auto;
  margin-right: 0;
  color: #999;
}

.location-text {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.bottom-actions {
  display: flex;
  padding: 30rpx;
  border-top: 1px solid #f0f2f5;
}

.cancel-btn,
.save-btn {
  flex: 1;
  margin: 0 10rpx;
  font-size: 28rpx;
  border-radius: 10rpx;
}

.cancel-btn {
  background-color: #f0f2f5;
  color: #666;
}

.save-btn {
  background-color: #3F7BFC;
  color: #fff;
}

.icon-svg {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.optional {
  color: #999;
  font-size: 24rpx;
  font-weight: normal;
  margin-left: 10rpx;
}
</style> 